const express = require("express");
const router = express.Router();
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);
let connectDAO = require("./connect.js");
async function dbTrainInfo(sql) {
  //为回调方法
  await connectDAO.queryDataBySQL(sql);
}

router.post("/set_user_statistics", function (req, res) {
  const { userId, username = "", source, behavior = "" } = req.query;
  console.log("调用了统计接口:", userId, source, behavior);
  if (userId && source) {
    connectDAO
      .queryDataBySQL(
        `SELECT userId FROM main WHERE userId = '${userId}' LIMIT 1`,
        (result) => {
          console.log("res", result);
          if (result.length > 0) {
            console.log("用户已存在，跳过插入操作");
            res.send({
              code: 210,
              msg: "User already exists, no action taken.",
            });
          } else {
            const registerTime = dayjs().tz("America/New_York").valueOf();
            connectDAO
              .queryDataBySQL(
                `INSERT INTO main VALUES ('${userId}', '${source}','${behavior}',FROM_UNIXTIME(${registerTime}/1000),'${username}',1,0)`
              )
              .then((data) => {
                res.send({ code: 200, msg: "user data statistics!" });
              })
              .catch((err) => {
                res.send({
                  code: 400,
                  msg: "user data statistics failed!:" + err,
                });
              });
          }
        }
      )
      .catch((err) => {
        res.send({ code: 201, msg: "user data statistics failed!" });
      });
  } else {
    res.send({
      mag: "parameter error",
      code: 400,
    });
  }
});

router.get("/get_user_statistics", function (req, res) {
  const { source } = req.query;
  const sql = source
    ? `SELECT * FROM user_source_statistics.main WHERE source = '${source}' ORDER BY updateTime`
    : "SELECT * FROM user_source_statistics.main ORDER BY updateTime";
  connectDAO
    .queryDataBySQL(sql, (result) => {
      if (result.length > 0) {
        res.send({
          code: 200,
          msg: "Success",
          result,
          total: result.length,
        });
      } else {
        res.send({
          code: 200,
          msg: "no data",
          result,
        });
      }
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

router.put("/put_user_statistics", function (req, res) {
  const { status = 1, isDelete = 0, userId } = req.body;
  console.log(" ", status, isDelete, userId);
  const sql = `UPDATE main SET status = ${+status}, isDelete = ${+isDelete} WHERE userId = '${userId}'`;
  connectDAO
    .queryDataBySQL(sql)
    .then(() => {
      res.send({ code: 200, msg: "success" });
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

// 行为统计
router.post("/take_notes_user_behavior", (req, res) => {
  const { userId, language_code, behavior_id, metadata = {} } = req.body;
  const registerTime = dayjs().tz("America/New_York").valueOf();
  const ip = req.headers["x-forwarded-for"]
    ? req.headers["x-forwarded-for"].split(",")[0].trim() // 获取 x-forwarded-for 中的第一个 IP
    : req.socket.remoteAddress;
  connectDAO
    .queryDataBySQL(
      `INSERT INTO user_behavior VALUES (DEFAULT, '${userId}', '${behavior_id}','${ip}','${language_code}',FROM_UNIXTIME(${registerTime}/1000),'${JSON.stringify(
        metadata
      )}')`
    )
    .then(() => {
      res.send({ code: 200, msg: "take notes user behavior statistics!" });
    })
    .catch((err) => {
      res.send({
        code: 400,
        msg: "failed!:" + err,
      });
    });
});

// 查询用户行为
/* 刷选条件：
    1. 行为id
    2. 用户昵称
*/

router.get("/get_user_behavior", (req) => {
  const { behavior_id } = req.query;
});

// 操作权限
router.get("/get_operate_permission", (req, res) => {
  const { userId, type } = req.query;
  const typeMap = {
    openPc: [7509171130, 6229880280,7419234917],
    col: [7509171130, 6229880280,7419234917],
    reloadInfo: [7509171130,8182696720,7419234917],
  };
  let data = {};
  if (typeMap[type].includes(+userId)) {
    data = {
      msg: "allow",
      permission: true,
    };
  } else {
    data = {
      msg: "ban",
      permission: false,
    };
  }
  res.send(data);
});

module.exports = router;
